// pages/short-video/index.ts
const app = getApp()
// import "./extend-page";
const watcher = require("../../behavior/watch");
const hideScrollBar = require("../../behavior/hide-scroll-bar")
import { queryShortVideoByPage, delShortVideoInteractive, addShortVideoInteractive, queryShortVideoComment, addShortVideoFeedback, getADV, getProductList, searchProduct, getSKUList, getProduct } from "../../api/index";
var timer;//连击计时器
Page({

  /**
   * 页面的初始数据
   */
  behaviors: [watcher, hideScrollBar],
  data: {
    pageHeight: app.globalData.pageHeight,
    windowWidth: app.globalData.windowWidth,
    videoCtx: null as any,

    videoList: [],
    current_index: 0,

    handleState: {
      attention: false
    },
    handleTapCount: 0,
    handleTapStartTime: 0,
    pageOption: {
      PageIndex: 1,
      PageSize: 10
    },
    activeId: "",

    isShowSearchComp: false,

    isShowComment: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(query) {
    wx.nextTick(() => {
      if (query.index) {
        this.setData({
          current_index: query.index
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getTabBar().init();
    this.setVideoData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    let videoList: any = this.data.videoList;
    const index = this.data.videoList.findIndex(ele => ele.Id == this.data.activeId);
    return {
      title: videoList[index].Describe,
      imageUrl: videoList[index].VlogCoverUrl,
      path: `/pages/short-video/index?index=${index}`
    }
  },

  videoTap() {
    this.data.playStates ? this.data.videoCtx.pause() : this.data.videoCtx.play();
    this.setData({
      playStates: !this.data.playStates
    })
  },
  onError(event) {
    console.log(event);

  },
  onPlay(event) {
    this.setData({
      activeId: event.detail.activeId
    });
    // const hasUserInfo = !(JSON.stringify(app.globalData.userInfo) == '{}');
    // if (hasUserInfo) {
    //   this.queryComment()
    // }
    // 处理分享封面，卡死 效率低
    // const shareShortVideo: any = this.data.videoList.filter((ele: any) => ele.Id == this.data.activeId)[0];
    // const index = this.data.videoList.findIndex(ele => ele.Id == this.data.activeId);
    // console.log(shareShortVideo);
    // this.handleCoverImg(shareShortVideo.VlogCoverUrl)

  },

  async swiperChange(event) {
    const hasUserInfo = !(JSON.stringify(app.globalData.hasUserInfo) == '{}');
    if (!hasUserInfo) return
    const { currentId } = event.detail;
    addShortVideoFeedback({ "ShortVideoId": currentId }).then(res => {
      console.log(res);
    });
  },

  // 视频点赞、评论、收藏、转发
  handlerDoubleHit() {
    let handleTapStartTime = this.data.handleTapStartTime;
    let handleTapCount = this.data.handleTapCount;
    const currenTime = new Date().getTime();
    handleTapCount = currenTime - handleTapStartTime < 300 ? handleTapCount + 1 : 1;
    this.setData({
      handleTapStartTime: currenTime,
      handleTapCount
    })
  },
  tapLike(event) {
    const { id, like } = event.detail;
    const params = {
      "OperateType": 1,
      "ShortVideoId": id,
      "Comment": ""
    }
    this.handlerDoubleHit();
    if (like) addShortVideoInteractive(params)
    if (!like) delShortVideoInteractive(params)
  },
  tapChat() {
    const hasUserInfo = !(JSON.stringify(app.globalData.userInfo) == '{}')
    if (!hasUserInfo) {
      wx.showToast({ title: "请在登录后查看", icon: "none" })
    }
    this.setData({ isShowComment: true });
  },
  updateComment(event) {//修改评论显示条数
    this.selectComponent("#comment-popup").setAddMsg(event.detail)
    this.selectComponent("#mp-video-swiper").updateCommentCount()
  },
  queryComment() {//查询评论
    this.selectComponent("#comment-popup").queryComment()
  },
  tapStar(event) {
    const { id, star } = event.detail;
    console.log(id, star);
    const params = {
      "OperateType": 2,
      "ShortVideoId": id,
      "Comment": ""
    }
    this.handlerDoubleHit();
    if (star) addShortVideoInteractive(params)
    if (!star) delShortVideoInteractive(params)
  },
  async tapShare(event) {
    const { id } = event.detail;
    const params = {
      "OperateType": 3,
      "ShortVideoId": id,
      "Comment": ""
    }
    addShortVideoInteractive(params)
  },
  tapAttention() {
    this.setData({
      "handleState.attention": true
    })
  },
  onUpdataVideo(event) {
    console.log(event);
    this.setData({
      "pageOption.PageIndex": this.data.pageOption.PageIndex + 1
    })
    this.setVideoData()
  },
  setVideoData() {
    queryShortVideoByPage({ PageOptions: this.data.pageOption }).then(res => {
      if (res.Data.length <= 0) return
      const urls = res.Data.map(item => ({ objectFit: "contain", ...item }));
      this.setData({
        videoList: urls
      })
    })
  },

  handleCoverImg(doctorImg) {
    return new Promise((resolve, reject) => {
      //传入图片地址
      let that = this;
      wx.createSelectorQuery()
        .select('#myCanvas') // 在 WXML 中填入的 id
        .fields({ node: true, size: true })
        .exec((res) => {
          // Canvas 对象
          console.log(res)
          const canvas = res[0].node
          // 渲染上下文
          const ctx = canvas.getContext('2d')

          // 图片对象
          const image = canvas.createImage()
          image.src = doctorImg
          console.log(image)
          image.onload = () => {
            let { width, height } = image
            // Canvas 画布的实际绘制宽高
            var widths = height * 5 / 4
            const dpr = wx.getWindowInfo().pixelRatio
            var w = (widths - width) / 2
            canvas.width = widths * dpr
            canvas.height = height * dpr
            ctx.scale(dpr, dpr)
            ctx.clearRect(0, 0, widths, height)
            // 将图片绘制到 canvas 上
            ctx.drawImage(image, w, 0)
            wx.canvasToTempFilePath({
              canvas,
              success: res => {
                // 生成的图片临时文件路径
                const tempFilePath = res.tempFilePath
                that.setData({ shareimg: tempFilePath })
                console.log(that.data.shareimg);
                resolve(that.data.shareimg)
              },
            })
          }
          image.onerror = (err) => {
            console.log(err)
            reject(err)
          }
          // 生成图片

        })
    })

  },
  tapCloseMask() {
    const goodsView = this.selectComponent(".short-video-goods-view");
    goodsView.tapCloseMask()
  },
  async tapShop(e) {
    const goodsView = this.selectComponent(".short-video-goods-view");
    goodsView.tapShop(e)
  },
  tapTopic(event) {
    const topic = event.detail;
    const params = {
      "Topic": topic, "Vlog_type": 0, "PageOptions": {
        "PageIndex": 1,
        "PageSize": 30,
      }
    }
    wx.navigateTo({
      url:`/pages/short-video-other/index?params=${JSON.stringify(params)}`
    })
  },

  tapInput() {
    // this.setData({
    //   isShowSearchComp: true
    // })
    wx.navigateTo({
      url: '/pages/short-video-other/index'
    })
  },
  tapBack() {
    this.setData({
      isShowSearchComp: false
    })
  },
  tapVideoCard(event) {
    const { id, params } = event.detail;
    wx.navigateTo({
      url: `/pages/short-video-other/index?id=${id}&params=${JSON.stringify(params)}`
    })
  }
})
export { }